const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class Promise {
    constructor(executor) {
        this.executor = executor;
        this.state = PENDING;
        this.value = undefined; // promise默认的FULFILLED的值
        this.reason = undefined; // promise默认的REJECTED的值
        this.onResolvedCallbacks = []; // 存放成功的回调函数
        this.onRejectedCallbacks = []; // 存放失败的回调函数
        const resolve = (value) => {
            if (this.state !== PENDING) return null;
            this.state = FULFILLED;
            this.value = value;
            this.onResolvedCallbacks.forEach(cb => cb(this.value));
        }

        const reject = (reason) => {
            if (this.state !== PENDING) return null;
            this.state = REJECTED;
            this.reason = reason;
            this.onRejectedCallbacks.forEach(cb => cb(this.value));
        }
        try {
            executor(resolve, reject);
        } catch (e) {
            reject(e);
        }
    }

    then(onFulfilled, onRejected) {
        if (this.state === FULFILLED) {
            onFulfilled()
        }
        if (this.state === REJECTED) {
            onRejected()
        }
        if (this.state === PENDING) {
            this.onResolvedCallbacks.push(onFulfilled);
            this.onRejectedCallbacks.push(onRejected);
        }
    }
}

module.exports = Promise;